package com.hmall.gateway.filter;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;
import java.util.List;

/**
 * @Author 86157
 * @Date 2025/9/2 下午5:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final JwtTool jwtTool;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getPath().toString();
        List<String>excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (pathMatcher.match(excludePath, uri)) {
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("Authorization");
        if(token == null||"".equals(token))
        {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Long userId=null;

        try {
            userId = jwtTool.parseToken(token);
        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
         request.mutate().header("user-info", userId.toString());
        log.info("用户id:{}", userId);
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
